import React, { Component } from 'react';
import ReactNative, { View, Text, ScrollView, Alert, TouchableOpacity } from 'react-native';
import NavSelection from '../../components/navSelection';
import { Flex, Toast, NoticeBar } from 'antd-mobile-rn';
import { captureRef, ViewShot } from "react-native-view-shot";
import api from '../../utils/api';
import cardService from '../../service/cardService';
import Utils from '../../utils';
import constants from '../../utils/constants';



export default class SubjectAdd extends Component {


    static navigationOptions = (e) => {

        const { state } = e.navigation;

        const onSaveClick = () => {

            state.params.onSaveClick();

        }

        return {
            headerTintColor: 'black',
            headerBackTitle: null,
            headerStyle: {
                backgroundColor: '#ffffff',
                borderBottomWidth: 0,
                shadowOpacity: 0,
                elevation: 0,
            },
            headerRight: (
                <Text onPress={onSaveClick} style={{ marginRight: 20, fontSize: 18, color: "#000", fontWeight: "300" }}>保存</Text>
            )
        }
    }

    state = {
        list: [],
        items: [],
        selectedItemIndex: null,
        selectColumns: {},
        ielts: [],
        examSets: [],
        selectedItems: [null, null, null],
        showNotice: false,
        saveRes: {
            errorNum: 0,
            score: 0.0
        },
        showRes:false
    }

    /**
     * 保存
     */
    saveCard = (success) => {

        Toast.loading("保存中...", 0);
        const cols = this.state.selectColumns;
        // ReactNative.takeSn
        console.log(this.refs.viewShot);
        captureRef(this.refs.viewShot, {
            format: "jpg",
            quality: 0.1,
            result: "base64",
            // snapshotContentContainer: true
        }).then(uri => {
            console.log("uri::", uri);
            api({
                url: "/examRecord/saveAnswer",
                method: "PUT",
                body: {
                    cardId: this.state.cardId,
                    image: uri,
                    userErrorAnswerDatas: Object.keys(cols).map(k => {
                        const col = cols[k];
                        return {
                            qno: col.no,
                            noteStatus: col.level,
                            qCategoryId: col.qCategoryId
                        }
                    })
                }
            }).then(data => {
                if (data.success) {
                    success();
                    //Toast.info("保存成功");
                    Toast.hide();
                    this.setState({
                        saveRes:data.result,
                        showRes:true
                    });

                    setTimeout(()=>{
                        this.setState({
                            showRes:false
                        });
                    },2000);
                    return;
                }
                Toast.info("保存失败");
            }).catch(data => {
                Toast.info("保存失败");
            })

        }, error => {
            console.log("error::", error);
        }
        )
    }

    componentDidMount() {
        const { navigation } = this.props;
        //保存按钮
        navigation.setParams({
            onSaveClick: () => {
                Alert.alert("确认答案输入无误?", "提交后将生成对应分数", [
                    { text: "再检查下" },
                    {
                        text: "确认提交", onPress: () => {

                            // this.refs.viewShot.capture().then(uri => {
                            //     console.log("do something with ", uri);
                            // });
                            this.saveCard(() => {
                                //取消已选择的
                                this.setState({
                                    selectColumns: {}
                                })
                                navigation.getParam("wrongRecordBack", () => { })();
                            });
                        }
                    }
                ])
            }
        })
        //加载数据
        this.initLoadItems(() => {
            //加载卡片数据
            this.loadAnswerCard();

        })

        Utils.getStorage("closeNoticeTitle").then(data => {

            if (!data) {
                this.setState({
                    showNotice: true
                })
            }
        })


    }





    /**
     * 加载列表选择数据
     */
    initLoadItems = (success) => {
        cardService.getIeltsAndExamSets().then(data => {


            const { examSetsMap, ieltMap } = data.result;
            this.setState({
                examSets: Object.keys(examSetsMap).map(key => {
                    return {
                        value: key,
                        label: examSetsMap[key]
                    }
                }),
                ielts: Object.keys(ieltMap).map(key => {
                    return {
                        value: key,
                        label: ieltMap[key]
                    }
                }),
            });

            const { ielts, examSets } = this.state;
            this.setState({
                selectedItems: [
                    ielts[0],
                    examSets[0],
                    { label: "听力", value: 1 }
                ]
            })
            success();
        });



    }

    /**
     * 
     */
    onColumnClick = (item) => {
        console.log("item::", item);
        const cols = this.state.selectColumns;
        let it = cols[item.no];
        if (!it) {
            it = {
                level: 1,
                no: item.no,
                qCategoryId: item.value.qCategoryId

            };
            cols[item.no] = it;
        } else {
            if (it.level == 1) {
                it.level = 2;
                console.log("it2:", it);
            }
            else if (it.level == 2) {
                delete cols[item.no];
            }
        }
        this.setState({
            selectColumns: cols
        })
    }


    /**
     * 加载卡片数据
     */
    loadAnswerCard = () => {
        const items = this.state.selectedItems;
        const params = {
            ieltsId: items[0].value,
            setId: items[1].value,
            section: items[2].value,
        }
        cardService.getAnswerCard(params).then(data => {

            const result = data.result;
            this.setState({
                cardId: result.cardId,
                list: result.answerCardDataVoList,
                selectColumns: {}
            })
        })
    }

    render() {

        const count = this.state.list.length > 0 ? parseInt(this.state.list.length / 2) : 0;

        const data = {
            left: [],
            right: []
        }

        this.state.list.forEach((value, i) => {
            if (i < count) {
                data.left.push({ no: i + 1, value: value });
            } else {
                data.right.push({ no: i + 1, value: value });
            }
        });

        const getBgColor = (no) => {
            const item = this.state.selectColumns[no];
            if (item) {
                if (item.level == 1) {
                    return "#ccc"
                }
                if (item.level == 2) {
                    return "#FBB03B"
                }
            }
            return "#ffffff";
        }

        const column = (item, i) => {
            return (
                <Flex key={i}>
                    <Flex.Item onPress={() => {
                        this.onColumnClick(item);
                    }} style={{ height: 35, overflow: "hidden", borderColor: "#ddd", borderWidth: 1, marginBottom: 5, flexDirection: "row", borderRadius: 3, backgroundColor: getBgColor(item.no) }}>
                        <View style={{ alignItems: "center", width: 35, justifyContent: "center", borderRightWidth: 1, borderRightColor: "#ddd" }}>
                            <Text style={{}}>{item.no}</Text>
                        </View>
                        <View style={{ justifyContent: "center", paddingRight: 2, overflow: "hidden" }}>
                            <Text style={{ marginLeft: 10, }}>{item.value.qKey}</Text>
                        </View>
                    </Flex.Item>
                </Flex>
            )
        }

        const seleds = this.state.selectedItems;
        const saveRes = this.state.saveRes;

        let examSets = [];

        if (seleds[0] && seleds[0].value == 12) {
            examSets = [
                {
                    label: "TEST5",
                    value: 5
                },
                {
                    label: "TEST6",
                    value: 6
                },
                {
                    label: "TEST7",
                    value: 7
                },
                {
                    label: "TEST8",
                    value: 8
                },
            ];


        } else {
            examSets = this.state.examSets;
        }

        const items = [
            {
                name: "剑桥",
                data: this.state.ielts
            },
            {
                name: "TEST",
                data: examSets
            },
            {
                name: "单项", data: [
                    { label: "听力", value: 1 },
                    { label: "阅读", value: 2 },

                ]
            }
        ]



        const showNotice = this.state.showNotice ? (

            <View style={{ flex: 1, position: "absolute", top: 200, width: "100%" }}>
                <TouchableOpacity onPress={() => {
                    Utils.setStorage("closeNoticeTitle", { "close": "yes" }).then(data => {
                        this.setState({
                            showNotice: false
                        })
                    });
                }}>
                    <NoticeBar mode={"closable"}>单击标示错题，双击标记难题</NoticeBar>
                </TouchableOpacity>
            </View>
        ) : undefined;


        const showResModal = this.state.showRes ? (

            <View 
            onStartShouldSetResponder={() => {
                this.setState({ showRes: false })
            }}
            style={{ flex: 1, alignItems: "center", justifyContent: "center", position: "absolute", top: 0, width: "100%", height: "100%" }}>

                <View style={{ width: 250, backgroundColor: "rgba(53,55,87,0.9)", alignItems: "center", borderRadius: 10 }}>
                    <View style={{ marginBottom: 15, width: 100, borderBottomColor: "#ddd", borderBottomWidth: 1, alignItems: "center", padding: 10 }} >
                        <Text style={{ color: "#fff" }}>保存成功</Text>
                    </View>
                    <View style={{ alignItems: "center", flexDirection: "row", marginBottom: 15 }}>
                        <Text style={{ color: "#fff", marginRight: 25, fontSize: 18, fontWeight: 'bold' }}>得分</Text>
                        <Text style={{ color: constants.activeColor, fontSize: 18, fontWeight: 'bold' }}>{saveRes.score}</Text>
                    </View>
                    <View style={{ alignItems: "center", flexDirection: "row", marginBottom: 15 }}>
                        <Text style={{ color: "#fff", marginRight: 25, fontSize: 18, fontWeight: 'bold' }}>错题数</Text>
                        <Text style={{ color: constants.activeColor, fontSize: 18, fontWeight: 'bold' }}>{saveRes.errorNum}个</Text>
                    </View>
                </View>

            </View>
        ) : undefined;


        return (
            <View style={{ backgroundColor: "#ffffff", flex: 1 }}>
                <NavSelection
                    selectedItems={seleds}
                    selectedIndex={this.state.selectedItemIndex}
                    items={items}
                    onItemClick={(item, index) => {
                        console.log("item:", item);

                        if (!item.value) {
                            return;
                        }




                        const items = this.state.selectedItems;

                        items[this.state.selectedItemIndex] = item;

                        if (this.state.selectedItemIndex == 0 && item.value != 12) {
                            items[1] = {
                                label: "TEST1",
                                value: 1
                            }
                        }


                        if (this.state.selectedItemIndex == 0 && item.value == 12) {
                            items[1] = {
                                label: "TEST5",
                                value: 5
                            }
                        }

                        this.setState({
                            selectedItems: items
                        });





                        this.loadAnswerCard()
                    }}
                    onNavLabelClick={(item, index) => {
                        this.setState({
                            selectedItemIndex: index
                        })
                    }}>


                    <ScrollView>
                        <View ref="viewShot" style={{ backgroundColor: "#fff", padding: 15, }}>


                            <Flex style={{ backgroundColor: "#ffffff", paddingTop: 0 }}>
                                <Flex.Item style={{ padding: 2, backgroundColor: "#ffffff" }}>
                                    {
                                        data.left.map((item, i) => {
                                            return column(item, i);
                                        })
                                    }
                                </Flex.Item>
                                <Flex.Item style={{ padding: 2, backgroundColor: "#fff" }}>
                                    {
                                        data.right.map((item, i) => {
                                            return column(item, i);
                                        })
                                    }
                                </Flex.Item>
                            </Flex>
                        </View>
                    </ScrollView>

                </NavSelection>
                {showNotice}
                {showResModal}


            </View>
        )
    }
}